package com.wenx.v3system.modular.platform.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wenx.v3system.modular.platform.domain.dto.PlatformUserAuthRequestDto;
import com.wenx.v3system.modular.platform.domain.dto.PlatformUserAuthResultDto;
import com.wenx.v3system.modular.platform.domain.po.PlatformUser;
import com.wenx.v3system.modular.platform.service.PlatformUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * 平台用户认证服务
 * 负责平台用户的密码验证逻辑
 *
 * @author wenx
 * @since 2024-01-20
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PlatformUserAuthService {

    private final PlatformUserService platformUserService;
    private final PasswordEncoder passwordEncoder;

    /**
     * 认证平台用户
     *
     * @param request 认证请求
     * @return 认证结果
     */
    public PlatformUserAuthResultDto authenticate(PlatformUserAuthRequestDto request) {
        try {
            // 根据标识符查找用户
            PlatformUser user = findUserByIdentifier(request.getIdentifier());
            if (user == null) {
                log.warn("平台用户认证失败：用户不存在，identifier={}", request.getIdentifier());
                return PlatformUserAuthResultDto.failure("用户不存在");
            }

            // 检查用户状态
            if (user.getStatus() == null || user.getStatus() != 1) {
                log.warn("平台用户认证失败：用户已停用，userId={}", user.getId());
                return PlatformUserAuthResultDto.failure("用户已停用");
            }

            // 验证密码
            if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
                log.warn("平台用户认证失败：密码错误，userId={}", user.getId());
                return PlatformUserAuthResultDto.failure("密码错误");
            }

            // 更新最后登录时间
            updateLastLoginTime(user.getId());

            // 转换最后登录时间
            LocalDateTime lastLoginTime = user.getLastLoginTime() != null ? 
                user.getLastLoginTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime() : null;

            log.info("平台用户认证成功：userId={}, username={}", user.getId(), user.getUsername());
            return PlatformUserAuthResultDto.success(
                user.getId(),
                user.getUsername(),
                user.getEmail(),
                user.getPhone(),
                user.getStatus(),
                lastLoginTime
            );

        } catch (Exception e) {
            log.error("平台用户认证异常：identifier={}", request.getIdentifier(), e);
            return PlatformUserAuthResultDto.failure("认证服务异常");
        }
    }

    /**
     * 根据标识符查找平台用户
     * 支持用户名、邮箱、手机号查询
     */
    private PlatformUser findUserByIdentifier(String identifier) {
        if (!StringUtils.hasText(identifier)) {
            return null;
        }

        // 优先按用户名查询
        PlatformUser user = platformUserService.getOne(
            new LambdaQueryWrapper<PlatformUser>()
                .eq(PlatformUser::getUsername, identifier)
                .eq(PlatformUser::getDeleted, 0)
        );
        
        if (user != null) {
            return user;
        }

        // 如果包含@符号，按邮箱查询
        if (identifier.contains("@")) {
            user = platformUserService.getOne(
                new LambdaQueryWrapper<PlatformUser>()
                    .eq(PlatformUser::getEmail, identifier)
                    .eq(PlatformUser::getDeleted, 0)
            );
            if (user != null) {
                return user;
            }
        }

        // 如果是11位数字，按手机号查询
        if (identifier.matches("\\d{11}")) {
            user = platformUserService.getOne(
                new LambdaQueryWrapper<PlatformUser>()
                    .eq(PlatformUser::getPhone, identifier)
                    .eq(PlatformUser::getDeleted, 0)
            );
        }

        return user;
    }

    /**
     * 更新用户最后登录时间
     */
    private void updateLastLoginTime(Long userId) {
        try {
            PlatformUser updateUser = new PlatformUser();
            updateUser.setId(userId);
            updateUser.setLastLoginTime(new Date());
            // 增加登录次数
            PlatformUser currentUser = platformUserService.getById(userId);
            if (currentUser != null) {
                updateUser.setLoginCount((currentUser.getLoginCount() == null ? 0 : currentUser.getLoginCount()) + 1);
            }
            platformUserService.updateById(updateUser);
        } catch (Exception e) {
            log.warn("更新用户最后登录时间失败：userId={}", userId, e);
        }
    }
}